#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2025/1/1 16:04
# @Author : George
"""
在 Selenium 4 中，不再直接在 webdriver.Chrome 中设置驱动程序路径，而是通过引入 Service 对象来设置。
这样可以避免弃用警告，并确保驱动程序的正确加载
"""
from selenium import webdriver
from selenium.webdriver.edge.service import Service as EdgeService
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import JavascriptException, TimeoutException
import time
import logging


def setup_driver():
    # 优化视频播放性能的设置
    options = webdriver.EdgeOptions()
    options.add_argument('--disable-gpu')  # 禁用GPU加速
    options.add_argument('--no-sandbox')  # 禁用沙箱模式
    options.add_argument('--disable-dev-shm-usage')  # 禁用/dev/shm使用
    options.add_argument('--disable-software-rasterizer')  # 禁用软件光栅化
    options.add_argument('--disable-extensions')  # 禁用扩展
    options.add_argument('--disable-infobars')  # 禁用信息栏
    options.add_argument('--autoplay-policy=no-user-gesture-required')  # 允许自动播放
    options.add_experimental_option('excludeSwitches', ['enable-automation'])  # 禁用自动化提示
    options.add_experimental_option("useAutomationExtension", False)  # 禁用自动化扩展

    # 设置正确的驱动路径
    service = EdgeService(executable_path='./msedgedriver.exe')
    return webdriver.Edge(options=options, service=service)


# def wait_for_video_end(driver, video_element):
#     """等待视频播放结束"""
#     try:
#         while True:
#             # 获取视频当前时间和总时长
#             current_time = driver.execute_script("return arguments[0].currentTime", video_element)
#             print(current_time)
#             duration = driver.execute_script("return arguments[0].duration", video_element)
#             print(duration)
#
#             # 如果视频播放结束或者无法获取时长，退出循环
#             if current_time >= duration or duration == 0:
#                 break
#
#             print(f"当前播放进度: {current_time:.2f}/{duration:.2f}")
#             time.sleep(5)  # 每5秒检查一次进度
#
#     except Exception as e:
#         print(f"视频播放监控出错: {str(e)}")
#

def main():
    driver = setup_driver()
    try:
        for i in range(1, 13):
            url = f"https://www.agedm.org/play/20070037/1/{i}"
            # 打开网站
            driver.get(url)
            # 切换到视频iframe
            driver.switch_to.frame("iframeForVideo")
            print(f"开始时间: {time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())}")

            # 等待视频元素加载
            wait = WebDriverWait(driver, 20)
            video_element = wait.until(
                EC.presence_of_element_located((By.CLASS_NAME, "art-video"))
            )
            print(f"找到视频元素: {video_element}")

            # 点击视频开始播放
            action = ActionChains(driver)
            action.move_to_element_with_offset(video_element, 100, 100).click().perform()
            print(f"点击播放时间: {time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())}")

            # 等待视频播放完成
            time.sleep(60*20)
            print(f"第{i}集播放完毕".center(100,"="))

    except Exception as e:
        print(f"发生错误: {str(e)}")
    finally:
        driver.quit()


if __name__ == "__main__":
    # http: // www.agedm.org / play / 20240205 / 1 / 1
    # http: // www.agedm.org / play / 20240205 / 1 / 2
    main()

